package com.example.dafafastlib.base;

import com.example.dafafastlib.Network.TResponse;
import com.example.dafafastlib.Network.TaskException;
import com.example.dafafastlib.utils.Logger;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by mocen_dafa on 2018/3/14.
 */

public class BaseModel {
    protected <T> Subscription sendRequest(Observable<TResponse<T>> observable,
                                           Action1<? super Object> onNext,
                                           Action1<Throwable> onError) {
        Subscription subscription = observable.flatMap((Func1<TResponse<T>, Observable<?>>) ttResponse -> {
            if (ttResponse.data != null)
                Logger.i("ffff", ttResponse.data.toString());
            if (ttResponse.isSuccess()) {
                return Observable.just(ttResponse.data);
            } else {
                return Observable.error(new TaskException(ttResponse.code, ttResponse.msg));
            }
        }).subscribeOn(Schedulers.io())// 指定 subscribe() 发生在 IO 线程
                .observeOn(AndroidSchedulers.mainThread()) // 指定 Subscriber 的回调发生在主线程
                .subscribe(onNext, onError);

        return subscription;
    }
}
